package com.hsnn.medstgmini.base.std.dao.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.impl.BaseHibernateDAO;
import com.hsnn.medstgmini.base.std.dao.StdCompprofileDao;
import com.hsnn.medstgmini.base.std.model.StdCompprofile;
import com.hsnn.medstgmini.base.std.model.StdCompprofileLog;
import com.hsnn.medstgmini.dao.HibernateSqlUtil;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 企业资质DAO实现类
 * @author 韩守松
 * @date 2015年8月21日
 */
@Repository
public class StdCompprofileDaoImpl extends BaseHibernateDAO implements StdCompprofileDao{
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtil sqlUtil;

	/**
	 * @category 查看企业资质信息
	 * @author 韩守松
	 * @date   2015年8月21日
	 * @param  @param page
	 * @param  @param stdCompprofile
	 * @param  @return
	 */
	public Pagination getStdCompprofile(Pagination page,StdCompprofile stdCompprofile) {
		StringBuffer hql = new StringBuffer();
		StringBuffer counthql = new StringBuffer();
		hql.append(" from StdCompprofile where comp_id = :compId ");
		counthql.append("select count(*) from StdCompprofile where comp_id = :compId ");
		
		if(StringUtils.isNotBlank(stdCompprofile.getProfileName())){
			hql.append(" and profile_name like :profileName ");	
		}
		Query queryCount = getSession().createQuery(counthql.toString());
		queryCount.setString("compId",stdCompprofile.getCompId());
		page.setRecords(Long.valueOf(queryCount.uniqueResult().toString()));
		Query query = getSession().createQuery(hql.toString());
		query.setString("compId", stdCompprofile.getCompId());
		if(StringUtils.isNotBlank(stdCompprofile.getProfileName())){
			query.setString("profileName", stdCompprofile.getProfileName());
		}
		query.setFirstResult((page.getPage()-1)*page.getMaxResults());
		query.setMaxResults(page.getMaxResults());
		page.setRows(query.list());
		return page;
	}

	@Override
	public Pagination save(Pagination page, StdCompprofile stdCompprofile) {
		stdCompprofile.setCompprofileId(UUID.randomUUID().toString());
		getSession().saveOrUpdate(stdCompprofile);
		getSession().flush();
		saveLog(stdCompprofile);
		return page;
	}

	/**
	 * @category 根据企业资质id获取资质信息
	 * @author 韩守松
	 * @date   2015年8月24日
	 * @param  @param compprofileId
	 * @param  @return
	 */
	public StdCompprofile getStdCompprofileById(String compprofileId){
		StringBuffer hql = new StringBuffer();
		hql.append(" from StdCompprofile scp where scp.compprofileId = :compprofileId ");
		Query query = getSession().createQuery(hql.toString());
		query.setString("compprofileId", compprofileId);
		return (StdCompprofile)query.uniqueResult();
	}
	
	@Override
	public Pagination edit(Pagination page, StdCompprofile stdCompprofile) {
		getSession().clear();
		getSession().saveOrUpdate(stdCompprofile);
		getSession().flush();
		saveLog(stdCompprofile);
		return page;
	}
	
	 /**
	  * @category 更新企业资质状态
	  * @author 韩守松
	  * @date   2015年8月25日
	  * @param  @param stdCompprofile
	  * @param  @return
	  */
	 public Pagination update(StdCompprofile stdCompprofile){
		 Pagination page = new Pagination();
		 getSession().saveOrUpdate(stdCompprofile);
		 getSession().flush();
		 
		 saveLog(stdCompprofile);
		 page.setSuccess(true);
		 return page;
	 }
	
	 /**
	  * @category 查询企业资质维护记录信息
	  * @author 韩守松
	  * @date   2015年8月25日
	  * @param  @param page
	  * @param  @param stdCompprofileLog
	  * @param  @return
	  */
	@SuppressWarnings({ "unchecked"})
	public List<Object> getStdCompprofileLogData(Pagination page,StdCompprofileLog stdCompprofileLog){
		Session session = sessionFactory.getCurrentSession();
		
		// 查询总记录数
		StringBuffer sb = new StringBuffer();
		sb.append("select count(*) ")
		.append(" FROM std_compprofile_log a LEFT JOIN dic_ent_profile b ON a.profile_type = b.dic_ent_profile_id LEFT JOIN sys_user c ON a.upd_user = c.id ")
		.append("  WHERE a.compprofile_id = :compprofileId   ");
		
		StringBuffer hql = new StringBuffer();
		hql.append(" SELECT a.log_id logId,a.detail,a.compprofile_id compprofileId, a.comp_id compId, a.profile_code profileCode, a.profile_name profileName, a.profile_type profileType, DATE_FORMAT( a.profile_starttime, '%Y-%m-%d' ) profileStarttime, DATE_FORMAT( a.profile_endtime, '%Y-%m-%d' ) profileEndtime, a.profile_pic_addr profilePicAddr, a.profile_pic_shortcut_addr profilePicShortcutAddr, a.status, a.remarks, a.audit_status auditStatus, DATE_FORMAT( a.audit_datetime, '%Y-%m-%d' ) auditDatetime, a.audit_remark auditRemark, c.name updUser, DATE_FORMAT(a.upd_datetime, '%Y-%m-%d %T') updDatetime, b.first_level_indi_code firstLevelIndiCode, b.first_level_indi_name firstLevelIndiName FROM std_compprofile_log a LEFT JOIN dic_ent_profile b ON a.profile_type = b.dic_ent_profile_id LEFT JOIN sys_user c ON a.upd_user = c.id WHERE a.compprofile_id = :compprofileId ");
		
		Date profileStarttime = stdCompprofileLog.getProfileStarttime();
		if (profileStarttime != null) {
			hql.append(" AND DATE_FORMAT(a.upd_datetime, '%Y-%m-%d' ) >= :profileStarttime ");
			sb.append(" AND DATE_FORMAT(a.upd_datetime, '%Y-%m-%d' ) >= :profileStarttime ");
		}
		
		Date profileEndtime = stdCompprofileLog.getProfileEndtime();
		if (profileEndtime != null) {
			hql.append(" AND DATE_FORMAT(a.upd_datetime, '%Y-%m-%d' ) <= :profileEndtime ");
			sb.append(" AND DATE_FORMAT(a.upd_datetime, '%Y-%m-%d' ) <= :profileEndtime ");
		}
		
		hql.append(" ORDER BY a.upd_datetime DESC ");
		
		SQLQuery queryCount = session.createSQLQuery(sb.toString());
		queryCount.setString("compprofileId",stdCompprofileLog.getCompprofileId());
		
		SQLQuery query = session.createSQLQuery(hql.toString());
		query.setString("compprofileId",stdCompprofileLog.getCompprofileId());
		
		if (profileStarttime != null) {
			queryCount.setDate("profileStarttime", profileStarttime);
			query.setDate("profileStarttime", profileStarttime);
		}
		if (profileEndtime != null) {
			queryCount.setDate("profileEndtime", profileEndtime);
			query.setDate("profileEndtime", profileEndtime);
		}
		
		Long total = Long.valueOf(queryCount.uniqueResult().toString());
		page.setRecords(total);
		query.setFirstResult((page.getPage()-1)*page.getMaxResults());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		return query.list();
	 }
	 
	/**
	 * @category 日志维护
	 * @author 韩守松
	 * @date   2015年8月25日
	 * @param  @param stdCompprofile
	 */
	public void saveLog(StdCompprofile stdCompprofile){
		
		Session session = getSession();
		// ----begin	
        StringBuffer detail = new StringBuffer();
		StringBuffer sb = new StringBuffer()
		.append("  select  profile_code profileCode, profile_name profileName, b.first_level_indi_name profileType, profile_pic_addr profilePicAddr, profile_pic_shortcut_addr profilePicShortcutAddr, remarks remarks, a.status status   ")
		.append(" from std_compprofile a LEFT JOIN dic_ent_profile b ON b.dic_ent_profile_id=a.profile_type where compprofile_id =  :compprofileId ")
		.append(" union all ")
		.append(" select t.* from (select  profile_code profileCode, profile_name profileName, b.first_level_indi_name profileType, profile_pic_addr profilePicAddr, profile_pic_shortcut_addr profilePicShortcutAddr, remarks remarks, a.status status ")
		.append("  from std_compprofile_log a   LEFT JOIN dic_ent_profile b ON b.dic_ent_profile_id=a.profile_type  where compprofile_id = :compprofileId  order by a.upd_datetime desc limit 1 ) t");
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("compprofileId", stdCompprofile.getCompprofileId());
		List<?> list = sqlUtil.getSqlList(sb.toString(), params);
		
		String[] colunm ={"资质编号","资质名称","资质类型","资质缩略图","备注","","状态"};
		if(list.size()==1){
			Object[] obj =(Object[]) list.get(0);
			obj[6] = obj[6]==null?"":"1".equals(obj[6].toString())?"启用":"停用";
			for(int i = 0;i<obj.length;i++){
				detail.append(";").append(colunm[i]).append(":").append(obj[i]==null?"":obj[i].toString());
			}
			detail.delete(0, 1);
		}else{
			Object[] obj1 =(Object[]) list.get(0);//修改后
			Object[] obj2 =(Object[]) list.get(1);//修改前
			obj1[6] = obj1[6]==null?"":"1".equals(obj1[6].toString())?"启用":"停用";
			obj2[6] = obj2[6]==null?"":"1".equals(obj2[6].toString())?"启用":"停用";
			for(int i = 0;i<obj1.length;i++){
				if(!(obj1[i]==null?"":obj1[i].toString()).equals(obj2[i]==null?"":obj2[i].toString())){
					detail.append(";").append(colunm[i]).append(":").append(obj2[i]==null?"":obj2[i].toString()).append(",").append(obj1[i]==null?"":obj1[i].toString());
				}
				
			}
			detail.delete(0, 1);
		}
		// ----end
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into std_compprofile_log(log_id,compprofile_id,comp_id,profile_code,profile_name,profile_type,profile_starttime,profile_endtime,profile_pic_addr,profile_pic_shortcut_addr,status, ")
			.append(" remarks,upd_datetime,upd_user,audit_status,audit_datetime,audit_remark,audit_user,detail ")
			.append(" ) select ")
		    .append(" UUID(),t.compprofile_id,t.comp_id,t.profile_code,t.profile_name,t.profile_type,t.profile_starttime,t.profile_endtime,t.profile_pic_addr,t.profile_pic_shortcut_addr,t.status,t.remarks,t.upd_datetime,t.upd_user, ")
		    .append(" t.audit_status,t.audit_datetime,t.audit_remark,t.audit_user,:detail from std_compprofile t where t.compprofile_id= :compprofileId ");
		Query query=session.createSQLQuery(sql.toString());
		query.setString("compprofileId",stdCompprofile.getCompprofileId());
		query.setString("detail",detail.toString());
		query.executeUpdate();
		session.flush();
	}
	
	
	
}
